<?php

/*
  Copyright (c) 2008 Abhi Beckert

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.
*/

require_once './include/initialize.php';

class WWController
{
  /**
   * the main function, this is executed for almost any page request
   */
  function run()
  {
    // prepare some varibales
    $this->headHtml = '';
    $this->editMode = false;
    $this->footerLinksHtml = '<a href="'.BASE_URL.'">Homepage</a> : <a href="'.$this->urlForAction('edit').'">Add new page</a>';
    
    // determine action
    $action = isset($_GET['action']) ? $_GET['action'] : 'view';
    $action = preg_replace('/[^a-z]+/', '', $action) . 'action';
    if (!method_exists($this, $action))
      $action = 'pageNotFoundAction';
    
    // force login action if necessary
    if (LOGIN_PASSWORD_HASH && (!isset($_SESSION['ww_password_hash']) || $_SESSION['ww_password_hash'] != LOGIN_PASSWORD_HASH) && $action != 'loginaction') {
      $action = 'loginformaction';
    }
    
    // run action
    $this->$action();
    
    // display output
    if (LOGIN_PASSWORD_HASH && isset($_SESSION['ww_password_hash']))
      $this->footerLinksHtml .= ' : <a href="'.$this->urlForAction('logout').'">Logout</a>';
    $this->output();
  }
  
  /**
   * print out the html of the page
   */
  function output()
  {
    // make all local variables available in the main scope of the template file
    foreach (get_object_vars($this) as $var => $value) {
      $$var = $value;
    }
    
    // include the template file
    require './template.php';
  }
  
  /**
   * generates an identifier from a user-entered page title
   */
  function identifierFromPageTitle($title)
  {
    // lowercase
    $identifier = strtolower($title);
    
    // alphanumeric and underscores only
    $identifier = preg_replace('/[^a-z0-9]+/', '_', $identifier);
    
    return $identifier;
  }
  
  function pageTitleFromIdentifier($identifier)
  {
    // replace underscores
    $title = str_replace('_', ' ', $identifier);
    
    // titlecase
    $title = ucwords($title);
    
    return $title;
  }
  
  /**
   * loads the title and content of a specific page from the database
   */
  function loadPage($identifier, &$title, &$content, $autofillContentForMissingPages=true)
  {
    // try to find the page in the database
    $pageRecord = WWModel::fetchPage($identifier);
    
    // if page not found, generate a placeholder with an edit message
    if (!$pageRecord) {
      $content = ($autofillContentForMissingPages ? 'This page does not exist yet. You may wish to <a href="'.$this->urlForAction('edit', $identifier).'">create it</a>.' : '');
      $pageRecord = array(
        'title' => $this->pageTitleFromIdentifier($identifier),
        'content' => $content,
      );
    }
    
    $title = $pageRecord['title'];
    $content = $pageRecord['content'];
  }
  
  /**
   * sends a 404 not found header and prepares a not found message
   */
  function pageNotFoundAction()
  {
    header('HTTP/1.0 404 Not Found');
    $this->pageIdentifier = '404';
    $this->pageTitle = htmlspecialchars('Error: Page Not Found');
    $this->pageContent = nl2br(htmlspecialchars("Sorry. The page you requested could not be found. Please check the URL and try again."));
  }
  
  /**
   * displays the page specified in $_GET['page'], which defaults to
   * "welcome" if it doesn't already exist.
   */
  function viewAction()
  {
    $this->pageIdentifier = isset($_GET['page']) ? $_GET['page'] : 'welcome';
    
    $this->loadPage($this->pageIdentifier, $this->pageTitle, $this->pageContent);
    
    $this->footerLinksHtml .= ' : <a href="'.$this->urlForAction('edit', $this->pageIdentifier).'">Edit this page</a>';
  }
  
  function editAction()
  {
    
    // load page
    $this->pageIdentifier = isset($_GET['page']) ? $_GET['page'] : '__new';
    if ($this->pageIdentifier == '__new') {
      $this->pageTitle = '';
      $this->pageContent = '';
    } else {
      $this->loadPage($this->pageIdentifier, $this->pageTitle, $this->pageContent, false);
    }
    
    if ($this->pageIdentifier == '')
      trigger_error('no page identifier provided', E_USER_ERROR);
    
    // prepare html
    $pageTitleValue = htmlspecialchars($this->pageTitle);
    $pageContentValue = htmlspecialchars($this->pageContent);
    $this->pageTitle = "Edit Page: {$this->pageTitle}";
    
    $this->headHtml .= <<<HTML
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/menu/assets/skins/sam/menu.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/button/assets/skins/sam/button.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/editor/assets/skins/sam/editor.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/element/element-beta-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/container/container_core-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/menu/menu-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/button/button-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/editor/editor-beta-min.js"></script>
HTML;
    
    $formTarget = $this->urlForAction('edit-submit');
    $cancelUrl = ($this->pageIdentifier == '__new') ? BASE_URL : $this->urlForAction('view', $this->pageIdentifier, false);
    $isNewPage = ($this->pageIdentifier == '__new') ? 'true' : 'false';
    
    $this->pageContent = <<<HTML
<form action="{$formTarget}" method="post">
  <input type="hidden" name="page" value="{$this->pageIdentifier}" />
  <p style="font-size: 1.4em;">Title: <input id="page_title" type="text" name="title" value="{$pageTitleValue}" /></p>
  <textarea id="content_editor" name="content" rows="20" cols="75">{$pageContentValue}</textarea>
  <p>
    <input id="cancel_btn" type="button" value="Cancel" />
    <input id="save_btn" type="submit" value="Save Changes" />
  </p>
</form>
<script type="text/javascript" charset="utf-8">
  (function() {
    var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event;

    var myConfig = {
      height: "350px",
      width: "730px",
      dompath: true,
      handleSubmit: true
    };
    if (!$isNewPage)
      myConfig.focusAtStart = true;

    var myEditor = new YAHOO.widget.Editor("content_editor", myConfig);
    myEditor._defaultToolbar.buttonType = "advanced";    
    myEditor.render();
    
    new YAHOO.widget.Button("cancel_btn", {type: 'link', href: '{$cancelUrl}'});
    new YAHOO.widget.Button("save_btn");
    
    if ($isNewPage)
      document.getElementById('page_title').focus();
  })();
  </script>
HTML;
  }
  
  function editSubmitAction()
  {
    $identifier = $_POST['page'];
    $title = $_POST['title'];
    $content = isset($_POST['content_rows=']) ? $_POST['content_rows='] : $_POST['content'];
    
    if ($identifier == '__new')
      $identifier = $this->identifierFromPageTitle($title);
    
    if (!$identifier) {
      header('location: '.BASE_URL);
      exit;
    }
    
    WWModel::insertNewVersionOfPage($identifier, $title, $content);
    
    header('location: '.$this->urlForAction('view', $identifier, false));
    exit;
  }
  
  function urlForAction($action, $page=null, $htmlEncoded=true)
  {
    $url = BASE_URL;
    
    if (NICE_URLS) {
      $url .= ($action != 'view' ? "/$action:" : '/'); // view is implied when no action is provided
      
      if ($page)
        $url .= $page;
    } else {
      $url .= "/index.php?action=$action";
      if ($page)
        $url .= "&page=$page";
    }
    
    if ($htmlEncoded)
      $url = htmlspecialchars($url);
    
    return $url;
  }
  
  function loginFormAction() {
    $this->pageTitle = 'Login';
    
    $this->headHtml = <<<HTML
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/menu/assets/skins/sam/menu.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/button/assets/skins/sam/button.css" />
<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.5.1/build/editor/assets/skins/sam/editor.css" />
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/element/element-beta-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/container/container_core-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/menu/menu-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/button/button-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.5.1/build/editor/editor-beta-min.js"></script>
HTML;
    
    $submitUrl = $this->urlForAction('login');
    $this->pageContent .= <<<HTML
<form method="post" action="{$submitUrl}">
  <p>Please enter your password:</p>
  <input type="password" name="password" id="password_field" />
  <p><input id="login_btn" type="submit" value="Login" /></p>
</form>

<script type="text/javascript" charset="utf-8">
  new YAHOO.widget.Button("login_btn");
  document.getElementById('password_field').focus();
</script>
HTML;
  
  $this->footerLinksHtml = '';
  }
  
  function loginAction() {
    $pwHash = sha1($_POST['password']);
    
    if ($pwHash != LOGIN_PASSWORD_HASH)
      return $this->loginFormAction();
    
    $_SESSION['ww_password_hash'] = $pwHash;
    header('location: '.BASE_URL);
    exit;
  }
  
  function logoutAction() {
    unset($_SESSION['ww_password_hash']);
    header('location: '.BASE_URL);
    exit;
  }
}

$controller = new WWController();
$controller->run();

?>
